package bar.dark.lee.alarm.beginalarm;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.format.Time;

public class BDAlarmManager
{
	public static final String ALERM_FLAG_POS = "alerm_flag_pos";
	
	private Context context;
	
	private BDAlarmManager(){};
	
	public BDAlarmManager(Context context)
	{
		this.context = context;
	}
	
	/**
	 * 알람을 지정된 시간에 시작하고 매일 반복한다.
	 * @param requestCode
	 * @param intent
	 * @param time
	 * @return
	 */
	public int setStartAlarm(int requestCode, Intent intent, String time)
	{
		try
		{
			PendingIntent sender = PendingIntent.getService(context, requestCode, intent, 0);
			
			AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			
			String [] times = time.split(",");
			int hourOfDay = Integer.parseInt(times[0]);
			int minute = Integer.parseInt(times[1]);
			
			Calendar cal = Calendar.getInstance();
			
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH);
			int day = cal.get(Calendar.DAY_OF_MONTH);
			
			int hour = cal.get(Calendar.HOUR_OF_DAY);
			int min = cal.get(Calendar.MINUTE);
			
			String tempMin = min + "";
			
			if (min < 10)
			{
				tempMin = "0" + min;
			}
			
			Calendar cal2 = Calendar.getInstance();
			cal2.set(year, month, day, hourOfDay, minute, 0000);
			
			String nowTime = hour + "" + tempMin + "";
			String tempTime = times[0] + times[1];
			
			if (Integer.parseInt(nowTime) > Integer.parseInt(tempTime))
			{
				cal2.roll(Calendar.DAY_OF_MONTH, true);
			}
			
			long triggerAtTime2 = cal.getTimeInMillis();
			long triggerAtTime = cal2.getTimeInMillis();
			
			am.setRepeating(AlarmManager.RTC, triggerAtTime, 1000*60*60*24, sender);
		} catch (Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		
		return 0;
	}
	
	/**
	 * 알람을 프로세스 상에서 제거 한다.
	 * @param requestCode
	 * @param intent
	 * @return
	 */
	public int cancelAlarm(int requestCode)
	{
		try
		{
			Intent intent = new Intent();
			
			PendingIntent sender = PendingIntent.getService(context, requestCode, intent, 0);
			
			AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			
			am.cancel(sender);
		} catch (Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		
		return 0;
	}
}
